import mongoose from 'mongoose';

const outfitSchema = new mongoose.Schema({

  // 搭配描述（备注）
  description: {
    type: String,
    trim: true
  },
  // 衣物ID数组
  clothesIds: {
    type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Clothes' }],
    default: []
  },
  // 季节数组（字符串类型）
  seasons: {
    type: [String],
    default: []
  },
  // 场景数组（字符串类型）
  occasions: {
    type: [String],
    default: []
  },
  // 搭配照（单张图片）
  outfitPhoto: {
    type: String,
    trim: true
  },
  // 搭配完的图片（Base64编码数据）
  finalOutfitImage: {
    type: String,
    required: true
  },
  // 搭配信息数组
  outfitInfo: {
    type: [Object],
    default: []
  },
  // 画布数据（JSON字符串）
  canvasData: {
    type: String,
    required: true
  },
  // 用户ID
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: true
});



// 静态方法：从所有相关穿搭中移除指定的衣物ID
outfitSchema.statics.removeClothesFromOutfits = async function(clothesId) {
  try {
    // 参数验证
    if (!clothesId) {
      throw new Error('衣物ID不能为空');
    }
    
    // 查找所有包含该衣物ID的穿搭
    const outfits = await this.find({ clothesIds: clothesId });
    
    let updatedCount = 0;
    
    // 从每个穿搭中移除该衣物ID
    for (const outfit of outfits) {
      outfit.clothesIds = outfit.clothesIds.filter(
        id => id.toString() !== clothesId.toString()
      );
      
      // 如果移除后穿搭还有衣物，则保存更新
      if (outfit.clothesIds.length > 0) {
        await outfit.save();
        updatedCount++;
      }
    }
    
    return updatedCount;
  } catch (error) {
    console.error('从穿搭中移除衣物失败:', error);
    throw error;
  }
};

// 静态方法：删除所有只包含指定衣物的穿搭
outfitSchema.statics.deleteOutfitsWithOnlyClothes = async function(clothesId) {
  try {
    // 参数验证
    if (!clothesId) {
      throw new Error('衣物ID不能为空');
    }
    
    // 查找所有只包含该衣物ID的穿搭
    const outfitsToDelete = await this.find({ 
      clothesIds: { $size: 1, $eq: [clothesId] }
    });
    
    // 删除这些穿搭
    const deleteResult = await this.deleteMany({ 
      clothesIds: { $size: 1, $eq: [clothesId] }
    });
    
    return deleteResult.deletedCount || 0;
  } catch (error) {
    console.error('删除只包含指定衣物的穿搭失败:', error);
    throw error;
  }
};

const Outfit = mongoose.model('Outfit', outfitSchema);

export default Outfit;